
package cn.ling.mini.spring.beans.factory;

import cn.ling.mini.spring.beans.factory.config.BeanDefinition;
import cn.ling.mini.spring.exception.BeanException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LING
 * @date 2024-10-10
 */
public class SimpleBeanFactory implements BeanFactory {

    private Map<String, BeanDefinition> beanDefinitions = new HashMap<>();
    private Map<String, Object> singletons = new HashMap<>();

    @Override
    public Object getBean(String beanName) throws BeanException {
        Object singleton = singletons.get(beanName);
        if (singleton == null) {
            if (!beanDefinitions.containsKey(beanName)) {
                throw new BeanException("bean不存在");
            }
            synchronized (this) {
                if (singleton == null) {
                    BeanDefinition beanDefinition = beanDefinitions.get(beanName);
                    try {
                        singleton = Class.forName(beanDefinition.getClassName()).newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    singletons.put(beanDefinition.getId(), singleton);
                }
            }
        }
        return singleton;
    }

    @Override
    public void registerBeanDefinition(BeanDefinition beanDefinition) {
        this.beanDefinitions.put(beanDefinition.getId(), beanDefinition);
    }
}
